// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    bills: [],
    CopyBills: [],
    today: '',
    todayshouzhi: {
      income: 0.00,
      expend: 0.00,
    },
    monthshouzhi: {
      income: 0.00,
      expend: 0.00,
      surplus: 0.00
    },
    //
    rootBills: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  formatDate(time) {
    let day = time;
    let year = day.getFullYear();
    let month = day.getMonth() + 1;
    let date = day.getDate();
    let format1 = [month, date].map(item => item < 10 ? "0" + item : item);
    let format2 = [year, month, date].map(item => item < 10 ? "0" + item : item).join("-");
    return {
      format1: `${format1[0]}月${format1[1]}日`,
      format2: format2,
      year,
      month: format1[0],
    }
  },
  //切换日期
  currDate(e) {
    // console.log(e);
    let value = e.detail.value.split("-");
    this.setData({
      today: {
        format1: `${value[1]}月31日`,
        format2: `${value[0]}-${value[1]}-31`,
        month: value[1],
        year: value[0]
      },
    });
    //获取当前月份结余
    this.getMonthBlace();
    // this.daysDispose();
  },
  //获取数据
  getDate(data) {
    //显示loading
    wx.showLoading({
      title: '加载中...',
    })
    wx.cloud.callFunction({
      name: "getData",
      data: data,
    }).then(res => {
      console.log(res);
      //关闭loading
      wx.hideLoading()

      this.setData({
        bills: res.result.data.reverse(),
      })
      //把每天的数据分割开来
      this.daysDispose();
    }).catch(err => {
      console.log("出错");
    })
  },
  //每天的数据处理
  daysDispose() {
    let obj = {};
    this.data.bills.forEach((item, index) => {
      if (!obj[item.today]) {
        obj[item.today] = {
          todaylist: [item],
          inandex: {
            day: item.today,
            income: item.type == "sr" ? item.money : 0,
            expend: item.type == "zc" ? item.money : 0
          }
        };
      } else {
        obj[item.today].todaylist.push(item);
        obj[item.today]['inandex']['income'] = item.type == "sr" ? +obj[item.today]['inandex']['income'] + +item.money : obj[item.today]['inandex']['income'];
        obj[item.today]['inandex']['expend'] = item.type == "zc" ? +obj[item.today]['inandex']['expend'] + +item.money : obj[item.today]['inandex']['expend'];
      }
    })
    this.setData({
      CopyBills: Object.values(obj),
    })
  },

  //本月收支
  monthBalance() {
    let income = 0;
    let expend = 0;
    this.data.rootBills.forEach((item) => {
      //本月收入
      if (item.type == "sr") income += +item.money;
      //本月支出
      if (item.type == "zc") expend += +item.money;
    })
    this.setData({
      monthshouzhi: {
        income: income.toFixed(2),
        expend: expend.toFixed(2),
        surplus: (income - expend).toFixed(2)
      }
    })
  },
  //获取当前月份天数
  mGetDate(year, month) {
    var d = new Date(year, month, 0);
    return d.getDate();
  },
  //跳转到记账页面
  toCharge() {
    wx.switchTab({
      url: '../charge/charge',
    })
  },
  //删除数据
  delete(e) {
    this.setData({
      bills: this.data.bills.filter(item => item._id != e.detail),
      rootBills: this.data.bills.filter(item => item._id != e.detail),
    });
    //从新处理每天的数据
    this.daysDispose();
    //获取本月结余
    this.monthBalance();
  },
  getMonthBlace() {
    let date = this.data.today.format2.split("-");
    let numdays = this.mGetDate(date[0], date[1]);
    wx.showLoading({
      title: '加载中...',
    })

    wx.cloud.callFunction({
      name: "month_incomeAndexpend",
      data: {
        start: `${date[0]}-${date[1]}-01`,
        end: `${date[0]}-${date[1]}-32`
      }
    }).then(res => {
      //关闭loading
      wx.hideLoading()
      this.setData({
        rootBills: res.result.data,
        bills: res.result.data,
      })
      this.monthBalance();
      this.daysDispose();
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      today: this.formatDate(new Date()),
    })


    //
    this.getMonthBlace();
  },

})